<template>
  <div class="ma-editor">
    <!-- 顶部：工具栏 -->
    <div class="ma-editor-header">
      <!-- 左侧操作区 -->
      <slot name="ma-toolBarLeft"></slot>

      <!-- 右侧操作区 -->
      <el-button-group class="ma-header-right">
        <el-button size="small" @click="maximizeOperation(index)" title="最大化">
          <el-icon>
            <FullScreen />
          </el-icon>
        </el-button>
        <el-button size="small" @click="moveOperationUp(index)" :disabled="index === 0">
          <el-icon>
            <ArrowUp />
          </el-icon>
        </el-button>
        <el-tooltip content="重置">
          <el-button size="small" @click="handleReset">
            <Icon icon="system-uicons:reset-alt" size="14" />
          </el-button>
        </el-tooltip>
        <el-tooltip  content="预览">
          <el-button size="small" @click="handlePreview">
            <Icon icon="ep:view" size="14" />
          </el-button>
        </el-tooltip>
        <el-tooltip content="保存">
          <el-button size="small" @click="handleSave">
            <Icon icon="ep:check" size="14" />
          </el-button>
        </el-tooltip>
      </el-button-group>
    </div>

    <div
      ref="editorContainer"
      class="ma-editor-container ma-container"
      :style="{ height: `${height}px` }"
    ></div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onBeforeUnmount, watch, ref, PropType } from 'vue'
import * as monaco from 'monaco-editor'
import { initializeMagicScript } from '@/components/MagicEditor/src/scripts/editor/magic-script'
import JavaClass from '@/components/MagicEditor/src/scripts/editor/java-class'
import { defineTheme, ScriptItem } from '@/components/MagicEditor/src/types/MagicConfig'
import defaultTheme from '@/components/MagicEditor/src/shared/themes/default-theme'
import darkTheme from '@/components/MagicEditor/src/shared/themes/dark-theme'
import { MagicThemeEnum } from '@/components/MagicEditor/src/shared/themes/theme'
import {ArrowUp, FullScreen} from "@element-plus/icons-vue";

defineOptions({
  name: 'MagicEditor'
})

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  language: {
    type: String as PropType<'json' | 'javascript' | 'typescript' | 'html' | 'css' | 'markdown'>,
    default: 'json'
  },
  theme: {
    type: String,
    default: MagicThemeEnum.Vs
  },
  height: {
    type: Number,
    default: 300
  }
})

const editorContainer = ref(null)
let editor: monaco.editor.IStandaloneCodeEditor | null = null

// const scripts = []
// const selected = null
// const info: ScriptItem = null
// const showImageDialog = false
// const imageUrl = ''
// const showHsitoryDialog = false

// self.MonacoEnvironment = {
//   getWorker: function (workerId, label) {
//     const workerMap = {
//       json: new URL('monaco-editor/esm/vs/language/json/json.worker.js', import.meta.url),
//       css: new URL('monaco-editor/esm/vs/language/css/css.worker.js', import.meta.url),
//       html: new URL('monaco-editor/esm/vs/language/html/html.worker.js', import.meta.url),
//       typescript: new URL('monaco-editor/esm/vs/language/typescript/ts.worker.js', import.meta.url),
//       javascript: new URL('monaco-editor/esm/vs/language/typescript/ts.worker.js', import.meta.url),
//       markdown: new URL(
//         'monaco-editor/esm/vs/language/markdown/markdown.worker.js',
//         import.meta.url
//       ),
//       default: new URL('monaco-editor/esm/vs/editor/editor.worker.js', import.meta.url)
//     }
//
//     return new Worker(workerMap[label] || workerMap.default, { type: 'module' })
//   }
// }

onBeforeMount(() => {

  Promise.all([JavaClass.initClasses(), JavaClass.initImportClass()]).then((e) => {

    initializeMagicScript()
  })

  defineTheme(MagicThemeEnum.Vs, defaultTheme)
  defineTheme(MagicThemeEnum.VsDark, darkTheme)
})

const emit = defineEmits(['update:modelValue'])

onMounted(() => {

  if (editorContainer.value) {
    // 确保容器高度正确
    editorContainer.value.style.height = `${props.height}px`
    editor = monaco.editor.create(editorContainer.value, {
      value: props.modelValue,
      language: props.language,
      theme: props.theme,
      automaticLayout: true,
      minimap: { enabled: false },
      scrollBeyondLastLine: false,
      lineNumbers: 'on',
      scrollbar: {
        vertical: 'auto',
        horizontal: 'auto'
      }
    })

    editor.addAction({
      id: 'editor.action.triggerSuggest.extension',
      label: '触发代码提示',
      precondition:
        '!suggestWidgetVisible && !markersNavigationVisible && !parameterHintsVisible && !findWidgetVisible',
      run: () => {
        editor?.trigger(null, 'editor.action.triggerSuggest', {})
      }
    })

    // 监听编辑器内容变化并更新
    editor.onDidChangeModelContent(() => {
      const value = editor?.getValue() || ''
      if (value !== props.modelValue) {
        emit('update:modelValue', value)
      }
    })

    // 强制布局更新
    setTimeout(() => {
      if (editor) {
        editor.layout()
      }
    }, 100)
  }
})

// 监听属性变化更新编辑器
watch(
  () => props.modelValue,
  (newValue) => {
    if (editor && newValue !== editor.getValue()) {
      editor.setValue(newValue)
    }
  }
)

watch(
  () => props.language,
  (newLang) => {
    if (editor) {
      monaco.editor.setModelLanguage(editor.getModel()!, newLang)
    }
  }
)

watch(
  () => props.height,
  (newHeight) => {
    if (editorContainer.value) {
      editorContainer.value.style.height = `${newHeight}px`
    }
    if (editor) {
      editor.layout()
    }
  }
)

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose()
  }
})
</script>
<style lang="scss" scoped>
$toolbar-height: 24px;

.ma-editor-header {
  display: none;
  height: $toolbar-height;
  border: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  position: relative;
}

.ma-header-right {
  position: absolute;
  right: 0;
  top: 0;
  height: $toolbar-height;
}

.ma-editor-container {
  //width: 100%;
  border: none;
  //border: 1px solid #dcdfe6;
  //border-radius: 4px;
  overflow: auto; /* 确保编辑器不溢出 */
}
</style>
